#include "CesTCacher.h"
#include "OCMain/HttpClient.h"
#include "OCMain/Log.h"
#include "json/json.h"

namespace OCPP
{
	const String baseUrl = "https://api.cesium.com/v1/assets/1/endpoint?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJlZDJjMTcwNS04ZDVmLTQzNWQtYWUyZC0yMTJkMDkyMzkyMjMiLCJpZCI6MTQ4MiwiaWF0IjoxNjQ4NDQ2OTIwfQ.7e1QUkx_k-mZBxKz9tV8a5TFEorrlLlkfcVNNPzfTQY";
	CesTCacher::CesTCacher(String url, String cachePath)
		:MapCacher(url, cachePath, "gz", {})
	{

	}

	CesTCacher::~CesTCacher()
	{

	}

	void CesTCacher::updateToken()
	{
		HttpClientEx httpClient([](const String& message)
			{
				OCPP_LOG_ERROR << message << "\n";
			});

		long retCode;
		String result = httpClient.fetchContent(baseUrl, retCode);
		if (retCode != 200)
		{
			return;
		}

		Json::Value root;
		Json::Reader reader;
		if (!reader.parse(result, root))
		{
			return;
		}

		_url = root["url"].asString();
		_accessToken = root["accessToken"].asString();
	}

	// https://assets.ion.cesium.com/ap-northeast-1/asset_depot/1/CesiumWorldTerrain/v1.2/0/0/0.terrain?extensions=octvertexnormals-watermask-metadata&v=1.2.0
	String CesTCacher::GenUrl(String layer, int z, int y, int x)
	{
		Date now = Date::now();
		if (_tokenGetTime.after(3600) < now)
		{
			_tokenGetTime = now;
			updateToken();
		}

		if (_accessToken.empty())
		{
			return "";
		}

		String url = MapCacher::GenUrl(layer, z, y, x);
		//mCesiumHeaders["Authorization"] = "Bearer " + _accessToken;
		return url;
	}
}
